//
//  FormDemo.swift
//  soapp_Example
//
//  Created by zhuxietong on 2019/4/16.
//  Copyright © 2019 CocoaPods. All rights reserved.
//

import Foundation
import soapp
import Eelay
import MBProgressHUD
import TPKeyboardAvoiding



class FormDemo: ListController {
    
    var isEdit = false
    
    var sections:TP.section{
        get{
            
            let cn_region = [mo.model["province",""],mo.model["city",""],mo.model["area",""]].joined(separator: " ").escapeHeadTailSpace()
            let region_json = Place.addressIDs(with: cn_region).json_value
            
            let sec = [
                [
                    ["id":"blank"]
                ],
                [
                    [
                        "title":"姓名".loc,
                        FK.fields:[
                            [
                                FK.placeholder:"请输入收货人姓名".loc,
                                FK.value:mo.model["realname",""],
                                FK.field:StrField(id: "realname", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "请输入收货人姓名".loc, err_msg: "检查姓名".loc))
                            ]
                        ],
                    ],
                    [
                        "title":"手机".loc,
                        FK.fields:[
                            [
                                FK.placeholder:"请输入手机号".loc,
                                FK.value:mo.model["mobile",""],
                                FK.field:StrField(id: "mobile", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg: EeLogin.phone, nil_msg: "请输入收货人手机号".loc, err_msg: "检查收货人手机号".loc))
                            ]
                        ],
                    ],
                    [
                        "title":"地区".loc,
                        "cellID":"area",
                        FK.fields:[
                            [
                                FK.placeholder:"选择地区".loc,
                                FK.value:region_json,
                                FK.field:StrField(id: "place", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg: "^[\\s\\S]{1,100000}$", nil_msg: "检查地区".loc, err_msg: "请检查地区".loc))
                            ]
                        ],
                    ],
                ],
                [
                    ["id":"blank56"]
                ],
            ]
            return sec
        }
    }
    let selector = [
        "id<blank>":BlankLine<line.px10>.self,
        "id<blank56>":BlankLine<line.px56>.self,
        "cellID<area>":FAddressCell.self,
        "<default>":SimpleTextCell.self

    ]
    
    
    
    override func viewDidLoad() {
        
        Place.db = DB.sqlite(db_name: "province.db", bundle: Bundle(for: DemoListCtr.self))
        Place.Tables.province.table = "provinces"
        Place.Tables.city.table = "cities"
        Place.Tables.area.table = "areas"
        
        Place.Tables.province.value = "code"
        Place.Tables.province.name = "name"
        
        Place.Tables.city.name = "name"
        Place.Tables.city.value = "code"
        Place.Tables.city.parent = "parent_code"
        
        
        Place.Tables.area.name = "name"
        Place.Tables.area.value = "code"
        Place.Tables.area.parent = "parent_code"
        
        title = "Gooo"

        
        tableView = TPKeyboardAvoidingTableView(frame: .zero, style: .plain)
        super.viewDidLoad()
        tableView.buildDynamicHeight(height: 60)
        tableView.backgroundColor =  UIColor.table_bg_color
        tableView.separatorStyle = .none
        tableView.tintColor = UIColor(shex: AppTheme.main_hex)
        
        
        FieldCell.name_width = 70
        FieldCell.padding_left = 21
        FieldCell.padding_right = 21
        
        top_style.navBarBgAlpha = 0
        top_style.navBarShadow = .color(UIColor.red)
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
            
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        
        // Do any additional setup after loading the view.
        //        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定", style: .plain, target: self, action: #selector(submitAction))
        //
        //        self.navigationItem.rightBarButtonItem?.tintColor = UIColor(shex:__main_hex)
        tableView.load(sections: sections, selector: selector)
        //        tableView.reloadData()
    }
    
    
    let bar = SubmitBar()
    
    override func layTable(tableView: UIView) {
        jo_contentView.eelay = [
            [bar,[ee.L.B.R],"60"],
            [tableView,[bar,ee.T,ee.B],[ee.L.R],[ee.T,TP.topHeight]],
        ]
        bar.controller = self
        let bt = bar.sbBt
        
        weak var ws = self
        bar.nextAction = {
            ws?.beginSubmit()
        }
        bt.ui.font(size: 15).ntitle(title: "提交".loc).ncolor(hex: "#fff").buttonColor(hex: AppTheme.main_hex)
       
    }
    
    
    override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        if actionID == "updateTable"
        {
            tableView.beginUpdates()
            tableView.endUpdates()
        }
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    deinit {
        print("+====================oooos")
    }
}

extension FormDemo{
    
    
    class SubmitBar: EeBottomBar {
        
        override var contentHeight: CGFloat{
            get{
                return 60
            }
        }
        let sbBt = UIButton()
        
        var nextAction:()->Void = { }
        
        override func addLayoutRules() {
            let line = UIView()
            contentView.eelay = [
                [line,[ee.T.L.R],"\(TP.separatorHeight)"],
                [sbBt,[ee.L.R.Y,[AppTheme.edge,-AppTheme.edge,0]],"36"],
            ]
            line.backgroundColor = UIColor.separator_color
            sbBt.ui.buttonColor(hex: UIColor.main_hex).ncolor(hex: "#fff").font(size: 13).padding(insets: [6,12]).ntitle(title: "提交".loc).set(radius: 4, width: nil, color: nil)
            sbBt.addTarget(self, action: #selector(confirmAction), for: .touchUpInside)
        }
        
        @objc func confirmAction(){
            nextAction()
        }
    }
    
    
    
}




extension FormDemo
{
    @objc func beginSubmit() {
        let info = JoPaw.paw(tableView: tableView)
        if info.validate{
            
            var values = info.values
            if isEdit{
                values["id"] = mo.detail["id",""]
            }
            self.commitAction(params: values)
        }
    }
    
    
    
    var orderID:String{
        get{
            return mo.model["id",""]
        }
    }
    
    func commitAction(params:[String:Any]) {
        
//        weak var wself = self
//        var hud:MBProgressHUD? = MBProgressHUD.init(for: wself!.navigationController!.view.window!)
//        if hud == nil{
//            hud = MBProgressHUD.showAdded(to: wself!.navigationController!.view.window!, animated: true)
//        }
//
//        if isEdit
//        {
//            hud?.label.text = "正在提交信息"
//        }
//
//        hud?.label.text = "正在提交信息"
//        let ps = params.mutable_dictionary
//        var vs = [String:Any]()
//        vs["type"] = ziliaoType.submitType
//
//        let content:[String:Any] = [
//            "name":ps["name",""],
//            "description":ps["description",""],
//        ]
//
//        vs["content"] = content.rawJson ?? "{}"
//
//
//
//        JoTask().post.log.log_response().params(vs).json_handle { (success, msg, obj, resp) in
//            if success{
//                //                if let _ = obj as? String{
//                hud?.hide(animated: true)
//                __post(notify: FNotice.studentProfileChange, object: nil, userInfo: nil)
//                wself?.success()
//                return
//                //                }
//            }
//            hud?.__show(msg, image: nil, minSize: nil)
//            }.run()
    }
    
    func success() {
        weak var wself = self
        if !isEdit{
            JoAlertView(info: "提示","学员信息提交成功".loc).append(title: "确认".loc) {
                wself?.navigationController?.popViewController(animated: true)
                }.show(at: self)
        }
        else{
            JoAlertView(info: "提示","学员信息提交成功".loc).append(title: "确认".loc) {
                wself?.navigationController?.popViewController(animated: true)
                }.show(at: self)
            
        }
    }
    
}




